<?php
/**
 * Created by PhpStorm.
 * User: jjj
 * Date: 2017/11/20
 * Time: 14:15
 */

namespace app\admin\controller;


use app\admin\lib\AdminController;
use app\admin\model\ApiResponse;
use app\common\model\curriculum\CurriculumVideo;
use app\common\model\VideoStorage;
use library\v163Class;
use think\Db;
use think\Exception;
use think\Log;

class Netease extends AdminController
{
    /**
     * 获取上传token接口
     *
     * @return ApiResponse
     */
    public function upload_token() {
        $form = $this->getAndCheckForm([
            ['file_name', 'require',],
            ['video_id', 'require|integer',],
        ]);

        $video_id = strval($form['video_id']);
        $video = CurriculumVideo::get($video_id);
        if (empty($video)) ApiResponse::error(ApiResponse::ERR_OPERATE_FAILED,'必须先创建视频后才能上传');

        $newFileName = date('YmdHis').'CurriculumVideo'.$video_id.'.'.pathinfo($form['file_name'],PATHINFO_EXTENSION);
        $userDefInfo = 'video_id='.$video_id;
        $re = v163Class::getInstance()
            ->vod_upload_init($form['file_name'], $newFileName,$userDefInfo);

        $vs = VideoStorage::get($video->vid);
        try{
            Db::startTrans();

            if (empty($vs)) {
                $vs = VideoStorage::create([
                    'netease_object' => $re['object'],
                    'netease_status' => VideoStorage::NETEASE_STATUS_UPLOADING
                ]);
                $video->vid = $vs->id;
            } else {
                $vs->netease_object = $re['object'];
                $vs->netease_status = VideoStorage::NETEASE_STATUS_UPLOADING;
                $vs->save();
            }
            $video->save();

            $video->setHide(true);

            Db::commit();
        }catch (\Exception $ex){
            Db::rollback();
        }

        return ApiResponse::success([
            'objectName' => $re['object'],
            'bucketName' => $re['bucket'],
            'nosToken' => $re['xNosToken'],
        ]);
    }

    /**
     * 获取视频详情
     *
     * @return ApiResponse
     */
    public function get_video_src() {
        $form = $this->getAndCheckForm([
            ['video_id', 'require|integer',],
        ]);

        $video = CurriculumVideo::get($form['video_id']);
        if (empty($video) || $video->vid <= 0) ApiResponse::error(ApiResponse::ERR_OPERATE_FAILED,'还未传视频');
        $vs = VideoStorage::get($video->vid);
        if (empty($vs)) ApiResponse::error(ApiResponse::ERR_OPERATE_FAILED,'还未传视频');
        if ($vs->netease_vid <= 0) ApiResponse::error(ApiResponse::ERR_OPERATE_FAILED,'视频上传还没完成');

        try{
            $ret = v163Class::getInstance()->vod_get($vs->netease_vid);
            return ApiResponse::success($ret);
        }catch (\Exception $ex){
            return ApiResponse::error(ApiResponse::ERR_OPERATE_FAILED, $ex->getMessage());
        }
    }

}